<template>
  <div class="editGq" @click="closeAllHistory">
    <el-dialog :visible.sync="centerDialogVisible"
               :close-on-click-modal="clickModalHide"
               :before-close="closeDialog"
                width="645px"
                top="12vh"
               :title="type=='add'?'新建工装':'编辑工装'">
      <el-form label-position="left" :model="editData" size="mini" status-icon :rules="rules" ref="editData"
               label-width="85px" style="margin-left: 15px"
               :inline="true" class="demo-ruleForm form_zl">
        <el-form-item label="工装编码：" prop="gzCode">
          <el-input v-model="editData.gzCode"   :disabled="type == 'edit'" placeholder="首字母大写"></el-input>
        </el-form-item>
        <el-form-item label="工段：" prop="gqId" class="label-dis">
          <el-select disabled v-model="editData.gqId" filterable placeholder="请选择">
            <el-option
              v-for="item in gdList"
              :key="item.id"
              :label="item.gqName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工装名称：" prop="gzName">
          <el-input v-model="editData.gzName" disabled></el-input>
        </el-form-item>
        <el-form-item label="工序：" prop="gxName">
          <el-select v-model="editData.gxName" filterable placeholder="请选择">
            <el-option
              v-for="(item,index) in gxList"
              :key="index"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品图号：" prop="produceCode">
          <el-input v-model="editData.produceCode"></el-input>
        </el-form-item>
        <el-form-item label="库位码：" prop="kuWeiCode">
          <el-select v-model="editData.kuWeiCode" filterable placeholder="请选择">
            <el-option
              v-for="(item,index) in kuList"
              :key="index"
              :label="item|grepName"
              :value="item ">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称：" prop="productName">
          <el-input v-model="editData.productName"></el-input>
        </el-form-item>
        <el-form-item label="保养日期：" prop="produceDate">
          <el-date-picker
            :disabled="type == 'edit'"
            style="width: 92%"
            v-model="editData.produceDate"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期：">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车型：" prop="carType">
          <el-input v-model="editData.carType"></el-input>
        </el-form-item>
        <el-form-item label="制作日期：" class="label-dis">
          <el-date-picker
            style="width: 92%"
            v-model="editData.byDate"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="领用部门：" prop="userDept" class="label-dis">
          <el-select v-model="editData.userDept" placeholder="请选择" class="select_zl">
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.deptName"
              :value="item.id">
              <span style="float: left">{{ item.deptName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deptLevel }}级</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="制作厂家：" class="label-dis">
          <el-input  v-model="editData.producer"
                     @keyup.native="selectItem($event)"></el-input>
          <div class="search-list-show" v-show="autoTip.length > 0 && tipShow" id="scrollElement_1">
            <ul class="choose-history" >
              <li v-for="(item,index) in autoTip"
                  :key="index"
                  :class="{'active':currentIndex == index}"
                  @click="chooseTip(item)">{{item}}</li>
            </ul>
          </div>
        </el-form-item>
        <el-form-item label="保管人：" prop="tokenUser" class="label-dis">
          <el-input v-model="editData.tokenUser"></el-input>
        </el-form-item>
        <el-form-item label="保养周期：" prop="maintainPeriod">
          <el-input v-model.number="editData.maintainPeriod" style="width: 70%"></el-input>
          <span>次/年</span>
        </el-form-item>
      </el-form>
      <div style="margin-left: 5%;color: red;line-height: 25px;">
        <div>附件上传</div>
        <div style="margin-top: 4px">
          <span>1.工装夹具验收单：</span>
          <input v-model="editData.ysName" readonly="true" class="input_1"/>
          <img src="../../../assets/images/download.png" style="width: 25px;cursor: pointer" @click="uploadYanShou" title="上传">
          <span v-show="editData.yanshouFullPath" style="color: blue; font-size: 13px;font-family: monospace;cursor: pointer;" @click="downLoadFile(editData.yanshouFullPath)">查看</span>
          <input type="file" id="gzys" style="display: none;" @change="uploadFileYs">
        </div>
        <div style="margin-top: 4px">
          <span>2.工装二维码：</span>
          <input v-model="editData.codeName" readonly="true" class="input_1" style="margin-left: 28px"/>
          <img src="../../../assets/images/download.png" style="width: 25px;cursor: pointer" @click="uploadCode" title="上传">
          <span v-show="editData.qrcodeFullPath" style="color: blue; font-size: 13px;font-family: monospace;cursor: pointer;" @click="downLoadFile(editData.qrcodeFullPath)">查看</span>
          <input type="file" id="code" style="display: none;" @change="uploadFileCode">
        </div>
      </div>
      <div style="text-align: center;margin-top: 15px">
        <el-button type="primary" @click="submitForm('editData')">提交</el-button>
        <el-button @click="resetForm('editData')">取消</el-button>
      </div>
      <form action="/autoMonitor/manage/downloadFile" method="post"
            style="display: none;" ref="downloadFile">
        <input name="path" :value="downPath"/>
      </form>

    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'editGz',
    props: ['dataDetail', 'type','kuweiMapResult','allGzList'],
    data() {
      var validateGz= (rule, value, callback) => {
        let gzList = [];
        if(this.allGzList && this.allGzList.length > 0){
          for(let data of this.allGzList){
            gzList.push(data.gzCode);
          }
        }
       if (gzList.includes(this.editData.gzCode)) {
          callback(new Error('工装代码已存在!'));
        } else {
          callback();
        }
      };
      return {
        centerDialogVisible: false,
        clickModalHide: false,
        editData: {
          ysName: "只允许JPG或PDF",
          codeName: "只允许JPG",
          id: "",
          gqName: "",
          gzName: "",
          dicId: "",
          gxName: "",
          kuWeiCode: "",
          gzCode: "",
          produceCode: "",
          productName: "",
          carType: "",
          producer: "",
          produceDate: "",
          byDate: "",
          maintainPeriod: "",
          yanshouPath: "",
          qrcodePath: "",
          userDept: "",
          tokenUser: ""
        },
        downPath:"",
        editTime: 0,
        gzMap: {},
        gdSelectMap: {},
        gdList: [],
        gxSelectMap: {},
        gxList: [],
        kuList: [],
        positionMap: {},
        produceNameList: [],
        autoTip: [],
        deptList: [],
        tipShow: false,
        clickTip: false,
        currentIndex:-1,
        isEnter:false,
        rules: {
          gzCode: [
            {validator: validateGz, trigger: 'blur'},
            {required: true, message: '请输入工装编码', trigger: 'blur'}
          ],
          // gqId: [
          //   {required: true, message: '请绑定工段',trigger: 'change'}
          // ],
          gzName: [
            {required: true, message: '请绑定工装名称', trigger: 'blur'}
          ],
          gxName: [
            {required: true, message: '请选择工序', trigger: 'change'}
          ],
          produceCode: [
            {required: true, message: '请输入产品图号', trigger: 'blur'}
          ],
          kuWeiCode: [
            {required: true, message: '请选择库位码', trigger: 'change'}
          ],
          productName: [
            {required: true, message: '请输入产品名称', trigger: 'blur'}
          ],
          produceDate: [
            {required: true, message: '请选择保养日期', trigger: 'blur'}
          ],
          byDate: [
            {required: true, message: '请选择制作日期', trigger: 'blur'}
          ],
          carType: [
            {required: true, message: '请输入车型', trigger: 'blur'}
          ],
          maintainPeriod: [
            {required: true, message: '请输入保养周期', trigger: 'blur'}
          ],
          producer: [
            {required: true, message: '请输入制作厂家', trigger: 'blur'}
          ]
        },
        count: 0,
      }
    },
    mounted() {
      let self = this;
      // this.getKuWei();
      this.getProduceName();
      this.getSelectDeptList();
    },

    computed: {
      gzCode() {
        return this.editData.gzCode;
      },
      maintainPeriod() {
        return this.editData.maintainPeriod;
      },

      producer() {
        return this.editData.producer;
      },
    },

    filters:{
      grepName(val){
        return val?val.substring(2,val.length):val;
      }
    },

    methods: {

      resetDept(){
        for(let item of this.deptList){
          if(item.id == this.editData.userDept){
            return;
          }
        }
        this.editData.userDept = "";
      },

      closeAllHistory(){
        this.tipShow = false;
        this.currentIndex = -1
      },
      selectItem(event){
        if(this.autoTip.length == 0){
          return;
        }
        if(event.code == "Enter"){
          this.isEnter = true;
          this.editData.producer = this.autoTip[this.currentIndex];
          return;
        }
        let scrollHeight = document.getElementById("scrollElement_1").scrollHeight;
        let height = document.getElementById("scrollElement_1").clientHeight;
        let dis = Math.round((scrollHeight - height)/this.autoTip.length);
        if(event.code == "ArrowDown" && this.currentIndex < this.autoTip.length-1){
          this.currentIndex++;
          document.getElementById("scrollElement_1").scrollTop =document.getElementById("scrollElement_1").scrollTop + dis;
        }
        if(event.code == "ArrowUp" && this.currentIndex > 0){
          document.getElementById("scrollElement_1").scrollTop =document.getElementById("scrollElement_1").scrollTop - dis;
          this.currentIndex --;
        }
      },

      downLoadFile(path){
        let self = this;
        self.downPath = path;
        self.$nextTick(()=>{
          self.$refs.downloadFile.submit();
        });
      },

      showPdf(data) {
        let self = this;
        self.$http({
          url: "/autoMonitor/bf/getFileBase",
          method: "post",
          params: {filePath: data}
        }).then(resp => {
          if (resp.success) {
            self.centerDialogVisible = true;
            self.pdfUrl = "data:application/pdf;base64," + resp.result;
          }
        });

      },

      getSelectDeptList() {
        let self = this;
        self.$http({
          url: "/autoMonitor/dept/queryDeptList",
          method: "post",
          params: {convertChild: false}
        }).then(resp => {
          if (resp.success) {
            self.deptList = resp.result;
          }
        });
      },

      chooseTip(tip) {
        this.editData.producer = tip;
        this.tipShow = false;
        this.clickTip = true;
      },

      uploadYanShou() {
        document.getElementById("gzys").click();
      },

      uploadCode() {
        document.getElementById("code").click();
      },

      uploadFileYs(event) {
        let self = this;
        let fileList = event.target.files;
        if (fileList.length > 0) {
          let file = fileList[0];
          if (/.(PDF|pdf|jpg|jpeg|png|gif)$/.test(file.name)) {
            self.editData.ysName = this.editData.gzCode ? this.editData.gzCode + "_ys" + file.name.substring(file.name.lastIndexOf(".")) : file.name;
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
              self.editData.yanshouPath = e.currentTarget.result;
            };
          } else {
            self.$notify({
              title: '提示',
              message: "上传文件必须是PDF或图片！！",
              type: 'warning'
            });
          }

        }
      },

      uploadFileCode(event) {
        let self = this;
        let fileList = event.target.files;
        if (fileList.length > 0) {
          let file = fileList[0];
          if (/.(jpg|jpeg|png|gif)$/.test(file.name)) {
            self.editData.codeName = this.editData.gzCode ? this.editData.gzCode + "_code" + file.name.substring(file.name.lastIndexOf(".")) : file.name;
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
              self.editData.qrcodePath = e.currentTarget.result;
            };
          } else {
            self.$notify({
              title: '提示',
              message: "上传文件必须是JPG！！",
              type: 'warning'
            });
          }
        }
      },

      compareDate(){
        let byDate = new Date(this.editData.byDate);
        let produceDate = new Date(this.editData.produceDate);
        if(byDate.getTime() > produceDate.getTime()){
          this.$notify({
            title: '提示',
            message: "制作日期要小于保养日期！",
            type: 'error'
          });
          return false;
        }
        return true;
      },

      operateGongZ() {
        let self = this;
        if (self.type == 'edit' && self.editData.yanshouPath.length < 100) {
          self.editData.yanshouPath = "";
        }
        if (self.type == 'edit' && self.editData.qrcodePath.length < 100) {
          self.editData.qrcodePath = "";
        }
        if(!self.compareDate()){
          return;
        }
        let url = this.type == 'add' ? '/autoMonitor/gz/addGongZhuang' : '/autoMonitor/gz/updateGongZhuang';
        if (this.count == 0) {
          self.$http({
            url: url,
            method: "post",
            data: JSON.stringify(self.editData),
            dataType: 'json',
            contentType: "application/json",
          }).then(resp => {
            if (resp.success) {
              self.resetForm('editData');
              self.$eventBus.$emit("updateGongzhuang", self.type);
              self.$notify({
                title: '提示',
                message: self.type == 'add' ? "添加成功！" : "修改成功",
                type: 'success'
              });
              return
            } else {
              self.$notify({
                title: '提示',
                message: resp.message,
                type: 'error'
              });
            }
            this.count--;
          });
          this.count++;
        }
      },

      //关闭弹窗
      closeDialog() {
        document.getElementById("gzys").value = "";
        document.getElementById("code").value = "";
        this.$refs['editData'].clearValidate();
        this.$refs['editData'].resetFields();
        this.centerDialogVisible = false;
      },

      submitForm(formName) {
        let self = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            self.operateGongZ();
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].clearValidate();
        this.closeDialog();
      },

      getResultAnalysis() {
        let result = this.kuweiMapResult;
        this.positionMap = {};
        this.gzMap = {};
        this.gdSelectMap = {};
        this.gxSelectMap = {};
        if (result && result.length > 0) {
          for (let data of result) {
            let position = data.positionHousesList;
            if (position && position.length > 0) {
              for (let _p of position) {
                if(!_p.useStatus ||_p.gzStatus =='10'|| _p.self){
                  if (!this.positionMap[_p.gzCode]) {
                    this.positionMap[_p.gzCode] = [];
                  }
                  this.positionMap[_p.gzCode].push(_p.code);
                }
              }
            }
            let gd = {gqName: data.gqName, id: data.id};
            if (data.gzList) {
              for (let _gz of data.gzList) {
                this.gzMap[_gz.code] = {name: _gz.name, id: _gz.id};
                this.gdSelectMap[_gz.code] = [gd];
                this.gxSelectMap[_gz.code] = _gz.gxList;
              }
            }
          }
          if(this.type == 'edit'){
            let first = this.editData.gzCode.substring(0, 1);
            let kuArray = this.positionMap[first];
            this.kuList = kuArray ? kuArray : [];
          }
        }
      },

      // getKuWei() {
      //   let self = this;
      //   self.$http({
      //     url: "/autoMonitor/gz/queryGqAndGzAndGxAndPosition",
      //     method: "post",
      //   }).then(resp => {
      //     if (resp.success) {
      //       self.getResultAnalysis(resp.result);
      //     }
      //   });
      // },
      getProduceName() {
        let self = this;
        self.$http({
          url: "/autoMonitor/gz/queryProducerName",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            self.produceNameList = resp.result;
          }
        });
      }
    },
    watch: {
      dataDetail(val) {
        let self = this;
        self.kuList = [];
        self.getResultAnalysis();
        this.count = 0;
        this.editTime = 0;
        this.centerDialogVisible = true;
        for (let key in this.editData) {
          if (!val.hasOwnProperty(key)) {
            this.$set(val,key,"");
          }
        }
        this.editData = val;
        if (this.type == 'edit' && this.editData.gzCode) {
          let first = this.editData.gzCode.substring(0, 1);
          let array = this.gdSelectMap[first];
          this.gdList = array ? array : [];
          this.editData.gqId = (array && array.length > 0) ? array[0].id : "";
        }
        self.resetDept();
        self.$nextTick(() => {
          self.tipShow = false;
        })
      },

      maintainPeriod(val) {
        for (let i = 0; i < val.length; i++) {
          if (!/^\d+$/.test(val[i])) {
            this.editData.maintainPeriod = this.editData.maintainPeriod.substring(0, i);
          }
        }
      },

      producer(val) {
        this.currentIndex = -1;
        let autoNames = [];
        if(this.isEnter){
          this.isEnter = false;
          this.tipShow = false;
          return;
        }
        for (let name of this.produceNameList) {
          if (name.indexOf(val) > -1 && val) {
            autoNames.push(name);
          }
        }
        if (!this.clickTip) {
          this.tipShow = true;
        }
        this.clickTip = false;
        this.autoTip = autoNames;
      },

      gzCode(val) {
        if (!(this.type == 'edit' && this.editTime == 0)) {
          this.editData.gxName = "";
          this.editData.kuWeiCode = "";
        }
        this.editTime++;
        let matches = /^[A-Z][A-z0-9]*$/;
        if (!matches.test(val)) {
          this.editData.gzCode = "";
          this.gdList = [];
          this.gxList = [];
          this.editData.gqId = "";
          this.editData.gxName = "";
          this.editData.gzName = "";
          this.editData.dicId = "";
          this.editData.kuWeiCode = "";
        } else {
          let first = val.substring(0, 1);
          let array = this.gdSelectMap[first];
          let gxArray = this.gxSelectMap[first];
          let kuArray = this.positionMap[first];
          this.editData.gzName = this.gzMap[first] ? this.gzMap[first].name : "";
          this.editData.dicId = this.gzMap[first] ? this.gzMap[first].id : "";
          this.gdList = array ? array : [];
          this.gxList = gxArray ? gxArray : [];
          this.kuList = kuArray ? kuArray : [];
          this.editData.gqId = (array && array.length > 0) ? array[0].id : "";
          if (this.editData.gzCode && this.editData.yanshouPath) {
            this.editData.ysName = this.editData.gzCode + "_ys" + this.editData.ysName.substring(this.editData.ysName.lastIndexOf("."));
          }
          if (this.editData.gzCode && this.editData.qrcodePath) {
            this.editData.codeName = this.editData.gzCode + "_code" + this.editData.codeName.substring(this.editData.codeName.lastIndexOf("."));
          }

        }
      }
    }
  }
</script>
<style>
  .editGq .el-form-item {
    margin-bottom: 15px;
  }

  .editGq .el-form--inline .el-form-item {
    margin-right: 12px;
  }

  .input_1{
    background: #e0dede;
    border: 1px;
    font-size: 12px;
    font-family: monospace;
    height: 26px;
    padding-left: 5px;
  }

  .search-list-show {
    position: absolute;
    top: 28px;
    left: 0;
    background-color: #fff;
    width: calc(100% - 2px);
    border: 1px solid #e4e4e4;
    box-shadow: 0 5px 5px rgba(0, 0, 0, 0.1);
    height: 450%;
    overflow-y:auto;
    z-index: 999 !important;
  }
  .search-list-show ul{
    padding: 0px;
  }

  .search-list-show li {
    list-style-type:none;
    margin: 10px;
    border-bottom: 1px dashed rgba(0, 128, 255, 0.1);
  }

  .search-list-show li:hover,
  .search-list-show li:focus {
    background-color: rgba(0, 128, 255, 0.1);
  }

  .editGq .el-form-item__label{
    padding: 0px 0px 0px 12px
  }

  .editGq .el-input--suffix .el-input__inner {
    padding-right: 17px;
  }

  .editGq .label-dis .el-form-item__label {
    padding: 0px 0px 0px 21px !important;
  }
  .choose-history .active{
    background-color: #6cc6ec3d;
  }
	.select_zl {
		width: calc(100% - 2px);
	}
</style>
